// 个人中心页面交互功能

document.addEventListener('DOMContentLoaded', function() {
    // 初始化用户信息
    initializeUserInfo();
    
    // 设置徽章点击事件
    setupBadgeClick();
    
    // 设置菜单项点击事件
    setupMenuItems();
    
    // 设置底部导航
    setupBottomNavigation();
    
    // 设置头像编辑
    setupAvatarEdit();
    
    // 设置设置按钮
    setupSettingsButton();
    
    // 设置通知按钮
    setupNotificationButton();
    
    // 模拟数据加载
    simulateDataLoading();
});

// 初始化用户信息
function initializeUserInfo() {
    // 模拟用户数据
    const userData = {
        name: '江心游客',
        level: '江心会员',
        vipLevel: 'VIP',
        checkinCount: 12,
        badgeCount: 5,
        favoriteCount: 3,
        points: 1280,
        nextLevelPoints: 2000,
        vipExpiry: '2024.12.31'
    };
    
    // 更新用户信息显示
    updateUserInfo(userData);
    
    // 添加加载动画
    const userInfoCard = document.querySelector('.bg-white.rounded-2xl.p-6');
    userInfoCard.classList.add('fade-in-up');
}

// 更新用户信息
function updateUserInfo(data) {
    // 更新用户名
    const userName = document.querySelector('h2.text-xl.font-bold.text-gray-800');
    if (userName) userName.textContent = data.name;
    
    // 更新统计数据
    const stats = document.querySelectorAll('.text-lg.font-bold');
    if (stats.length >= 3) {
        stats[0].textContent = data.checkinCount; // 打卡次数
        stats[1].textContent = data.badgeCount;     // 徽章数量
        stats[2].textContent = data.favoriteCount;  // 收藏数量
    }
    
    // 更新积分信息
    const pointsElement = document.querySelector('.text-sm.opacity-90');
    if (pointsElement) {
        pointsElement.textContent = `当前积分: ${data.points}`;
    }
    
    // 更新进度条
    const progressFill = document.querySelector('.bg-white.rounded-full.h-2 div');
    if (progressFill) {
        const progress = (data.points / data.nextLevelPoints) * 100;
        progressFill.style.width = `${progress}%`;
    }
    
    // 更新VIP等级
    const vipLevel = document.querySelector('.text-2xl.font-bold');
    if (vipLevel) vipLevel.textContent = data.vipLevel;
    
    // 更新有效期
    const expiry = document.querySelector('.text-xs.opacity-90');
    if (expiry) expiry.textContent = `有效期至 ${data.vipExpiry}`;
}

// 设置徽章点击事件
function setupBadgeClick() {
    const badgeItems = document.querySelectorAll('.badge-item');
    
    badgeItems.forEach(item => {
        item.addEventListener('click', function() {
            const badgeType = this.dataset.badge;
            const isEarned = this.classList.contains('earned');
            
            if (isEarned) {
                showBadgeDetail(badgeType);
            } else {
                showBadgeRequirement(badgeType);
            }
            
            // 添加点击动画
            this.style.transform = 'scale(0.95)';
            setTimeout(() => {
                this.style.transform = 'scale(1)';
            }, 150);
        });
    });
}

// 显示徽章详情
function showBadgeDetail(badgeType) {
    const badgeData = {
        'explorer': {
            name: '探索者',
            icon: 'fa-compass',
            description: '完成江心屿所有景点的打卡，成为真正的探索者！',
            earnedDate: '2024.01.15',
            points: 100
        },
        'photographer': {
            name: '摄影师',
            icon: 'fa-camera',
            description: '在江心屿拍摄并分享10张精美照片，记录美好瞬间。',
            earnedDate: '2024.01.20',
            points: 80
        },
        'collector': {
            name: '收藏家',
            icon: 'fa-shopping-bag',
            description: '在文创商城购买5件商品，支持江心屿文化传承。',
            earnedDate: '2024.01.25',
            points: 120
        },
        'historian': {
            name: '历史学者',
            icon: 'fa-scroll',
            description: '完成所有AR历史讲解，深入了解江心屿的历史文化。',
            earnedDate: '2024.02.01',
            points: 150
        },
        'master': {
            name: '大师',
            icon: 'fa-crown',
            description: '获得所有其他徽章，成为江心屿真正的文化大师。',
            earnedDate: null,
            points: 500
        }
    };
    
    const badge = badgeData[badgeType];
    if (badge) {
        createBadgeModal(badge);
    }
}

// 显示徽章要求
function showBadgeRequirement(badgeType) {
    const requirementData = {
        'master': {
            name: '大师',
            description: '需要获得探索者、摄影师、收藏家、历史学者四个徽章',
            progress: '3/4',
            remaining: '还需要获得1个徽章'
        }
    };
    
    const requirement = requirementData[badgeType];
    if (requirement) {
        showRequirementModal(requirement);
    }
}

// 创建徽章详情模态框
function createBadgeModal(badge) {
    const modal = document.createElement('div');
    modal.className = 'badge-modal';
    modal.innerHTML = `
        <div class="badge-modal-content">
            <div class="badge-modal-icon">
                <i class="fas ${badge.icon}"></i>
            </div>
            <h3 class="badge-modal-title">${badge.name}</h3>
            <p class="badge-modal-description">${badge.description}</p>
            ${badge.earnedDate ? `
                <p class="badge-modal-date">获得时间: ${badge.earnedDate}</p>
                <p class="text-xs text-green-600 font-medium">+${badge.points} 积分</p>
            ` : '<p class="text-xs text-gray-500">未获得此徽章</p>'}
            <button class="badge-modal-close" onclick="this.closest('.badge-modal').remove()">确定</button>
        </div>
    `;
    
    document.body.appendChild(modal);
    
    // 点击外部关闭
    modal.addEventListener('click', function(e) {
        if (e.target === modal) {
            modal.remove();
        }
    });
    
    // 3秒后自动关闭
    setTimeout(() => {
        if (modal.parentNode) {
            modal.remove();
        }
    }, 3000);
}

// 显示要求模态框
function showRequirementModal(requirement) {
    const modal = document.createElement('div');
    modal.className = 'badge-modal';
    modal.innerHTML = `
        <div class="badge-modal-content">
            <h3 class="badge-modal-title">${requirement.name}</h3>
            <p class="badge-modal-description">${requirement.description}</p>
            <p class="text-sm text-gray-600 mb-2">进度: ${requirement.progress}</p>
            <p class="text-xs text-gray-500 mb-4">${requirement.remaining}</p>
            <button class="badge-modal-close" onclick="this.closest('.badge-modal').remove()">确定</button>
        </div>
    `;
    
    document.body.appendChild(modal);
    
    // 点击外部关闭
    modal.addEventListener('click', function(e) {
        if (e.target === modal) {
            modal.remove();
        }
    });
}

// 设置菜单项点击事件
function setupMenuItems() {
    const menuItems = document.querySelectorAll('.menu-item');
    
    menuItems.forEach(item => {
        item.addEventListener('click', function(e) {
            e.preventDefault();
            
            const text = this.querySelector('span').textContent;
            handleMenuClick(text);
            
            // 添加点击动画
            this.style.background = '#e2e8f0';
            setTimeout(() => {
                this.style.background = '';
            }, 200);
        });
    });
}

// 处理菜单点击
function handleMenuClick(menuName) {
    switch(menuName) {
        case '浏览历史':
            showToast('浏览历史功能开发中...');
            break;
        case '我的收藏':
            showToast('收藏功能开发中...');
            break;
        case '购物车':
            showToast('购物车功能开发中...');
            break;
        case '积分商城':
            showToast('积分商城功能开发中...');
            break;
        case '优惠券':
            showToast('优惠券功能开发中...');
            break;
        case '足迹地图':
            showToast('足迹地图功能开发中...');
            break;
        case '我的相册':
            showToast('相册功能开发中...');
            break;
        case '帮助中心':
            showToast('帮助中心功能开发中...');
            break;
    }
}

// 设置底部导航
function setupBottomNavigation() {
    const navItems = document.querySelectorAll('.fixed.bottom-0 .text-center');
    
    navItems.forEach((item, index) => {
        item.addEventListener('click', function() {
            // 移除所有活动状态
            navItems.forEach(nav => {
                const icon = nav.querySelector('i');
                const text = nav.querySelector('p');
                icon.classList.remove('text-green-600');
                icon.classList.add('text-gray-400');
                text.classList.remove('text-green-600');
                text.classList.add('text-gray-400');
            });
            
            // 设置当前项为活动状态
            const currentIcon = this.querySelector('i');
            const currentText = this.querySelector('p');
            currentIcon.classList.remove('text-gray-400');
            currentIcon.classList.add('text-green-600');
            currentText.classList.remove('text-gray-400');
            currentText.classList.add('text-green-600');
            
            // 导航逻辑
            const pageNames = ['home', 'map', 'checkin', 'shop', 'profile'];
            const targetPage = pageNames[index];
            
            if (targetPage !== 'profile') {
                console.log(`导航到 ${targetPage}.html`);
                // 这里可以添加实际的页面跳转逻辑
            }
        });
    });
}

// 设置头像编辑
function setupAvatarEdit() {
    const avatarEdit = document.querySelector('.avatar-edit');
    const userAvatar = document.querySelector('.user-avatar img');
    
    if (avatarEdit && userAvatar) {
        avatarEdit.addEventListener('click', function() {
            const input = document.createElement('input');
            input.type = 'file';
            input.accept = 'image/*';
            input.onchange = function(e) {
                const file = e.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        userAvatar.src = e.target.result;
                        showToast('头像更新成功！');
                    };
                    reader.readAsDataURL(file);
                }
            };
            input.click();
        });
    }
}

// 设置设置按钮
function setupSettingsButton() {
    const settingsBtn = document.querySelector('.fa-cog').parentElement;
    
    settingsBtn.addEventListener('click', function() {
        showToast('设置功能开发中...');
        
        // 添加旋转动画
        this.style.transform = 'rotate(180deg)';
        setTimeout(() => {
            this.style.transform = 'rotate(0deg)';
        }, 300);
    });
}

// 设置通知按钮
function setupNotificationButton() {
    const notificationBtn = document.querySelector('.fa-bell').parentElement;
    
    notificationBtn.addEventListener('click', function() {
        showToast('暂无新通知');
        
        // 添加铃声动画
        this.style.animation = 'bellRing 0.5s ease-in-out';
        setTimeout(() => {
            this.style.animation = '';
        }, 500);
    });
}

// 模拟数据加载
function simulateDataLoading() {
    // 显示加载状态
    showLoadingState();
    
    // 模拟加载延迟
    setTimeout(() => {
        hideLoadingState();
        showSuccessMessage('数据加载完成');
    }, 1500);
}

// 显示加载状态
function showLoadingState() {
    const loadingElements = document.querySelectorAll('.text-lg.font-bold');
    loadingElements.forEach(element => {
        element.innerHTML = '<div class="loading-skeleton" style="width: 40px; height: 20px; border-radius: 4px;"></div>';
    });
}

// 隐藏加载状态
function hideLoadingState() {
    const loadingElements = document.querySelectorAll('.loading-skeleton');
    loadingElements.forEach(element => {
        element.remove();
    });
}

// 显示成功消息
function showSuccessMessage(message) {
    const toast = document.createElement('div');
    toast.className = 'success-toast';
    toast.innerHTML = `<i class="fas fa-check-circle mr-2"></i>${message}`;
    document.body.appendChild(toast);
    
    setTimeout(() => {
        toast.remove();
    }, 2000);
}

// 显示提示
function showToast(message) {
    const toast = document.createElement('div');
    toast.textContent = message;
    toast.style.position = 'fixed';
    toast.style.top = '100px';
    toast.style.left = '50%';
    toast.style.transform = 'translateX(-50%)';
    toast.style.background = 'rgba(0,0,0,0.8)';
    toast.style.color = 'white';
    toast.style.padding = '12px 24px';
    toast.style.borderRadius = '24px';
    toast.style.fontSize = '14px';
    toast.style.zIndex = '1000';
    toast.style.animation = 'fadeInOut 2s ease-out forwards';
    
    document.body.appendChild(toast);
    
    setTimeout(() => {
        toast.remove();
    }, 2000);
}

// 添加动画样式
const style = document.createElement('style');
style.textContent = `
    @keyframes fadeInOut {
        0% { opacity: 0; transform: translateX(-50%) translateY(-10px); }
        20% { opacity: 1; transform: translateX(-50%) translateY(0); }
        80% { opacity: 1; transform: translateX(-50%) translateY(0); }
        100% { opacity: 0; transform: translateX(-50%) translateY(-10px); }
    }
    
    @keyframes bellRing {
        0%, 100% { transform: rotate(0deg); }
        25% { transform: rotate(-15deg); }
        75% { transform: rotate(15deg); }
    }
    
    @keyframes successFade {
        0% {
            opacity: 0;
            transform: translate(-50%, -50%) scale(0.8);
        }
        20% {
            opacity: 1;
            transform: translate(-50%, -50%) scale(1);
        }
        80% {
            opacity: 1;
            transform: translate(-50%, -50%) scale(1);
        }
        100% {
            opacity: 0;
            transform: translate(-50%, -50%) scale(0.8);
        }
    }
`;
document.head.appendChild(style);